package com.bzzoneit.newsys.web.admin;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bzzoneit.newsys.entity.admin.Menu;
import com.bzzoneit.newsys.entity.admin.User;
import com.bzzoneit.newsys.service.admin.MenuService;
import com.bzzoneit.newsys.utils.dwz.AjaxDone;
import com.bzzoneit.newsys.utils.dwz.JsonResult;
import com.bzzoneit.newsys.utils.page.Page;
import com.bzzoneit.newsys.utils.web.Exceptions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@Controller
@RequestMapping("/menu")
public class MenuController extends BaseController {


	@Autowired
	private MenuService menuService;
	
	private Page<User> page;

	public Page<User> getPage() {
		return page;
	}

	public void setPage(Page<User> page) {
		this.page = page;
	}

	/**
	 * page 获得从页面传过来的分页信息
	 * 
	 * @param page
	 * @param model
	 * @return
	 */
	@RequestMapping("/list")
	public String list(@RequestParam("navtabid") String navtabid,
			Model model) {
		model.addAttribute("navtabid", navtabid);
		return "menu/list";
	}

	@RequestMapping("/tree")
	public String tree(Model model) {
		return "menu/tree";
	}

	@ResponseBody
	@RequestMapping("/dotree")
	public List<Menu> dotree() {
		return menuService.getAllMenuList();
	}	
	
	@ResponseBody
	@RequestMapping("/savetree")
	public JsonResult savetree(@RequestBody String u) {
		ObjectMapper mapper = new ObjectMapper(); 
		try {
			 List<Menu> nodes = mapper.readValue(u, TypeFactory.collectionType(List.class, Menu.class));
			 //保存对应的tree
			// Collections.sort(nodes);
			 saveTree(nodes);
			 //保存呢
		} catch (JsonParseException e) {
			e.printStackTrace();
			return new JsonResult(false,Exceptions.getStackTraceAsString(e));
		} catch (JsonMappingException e) {
			e.printStackTrace();
			return new JsonResult(false,Exceptions.getStackTraceAsString(e));
		} catch (IOException e) {
			e.printStackTrace();
			return new JsonResult(false,Exceptions.getStackTraceAsString(e));
		}
	
		return new JsonResult(true,"return ok");
	}

	private void saveTree(List<Menu> nodes) {
		//先遍历删除id不在这里面 需要删除t_menu,及t_menu_role2个表

		List<Long> list=Lists.newArrayList();
		System.out.println(nodes);
		Map<Long,List<Menu>> map= Maps.newHashMap();
		List<Menu> temp=Lists.newArrayList();
		int sortNum;
		//再更新或插入新的数据  按pid 的方式 并设置好 sortnumber
		for(Menu m:nodes){
			list.add(m.getId());
			Long pid=m.getParent_id();
			temp=map.get(pid);
			if(temp==null) temp=Lists.newArrayList();
			if(temp.size()==0){
				m.setSortNum(1);	
				temp.add(m);
				map.put(pid, temp);
			}
			else{
				sortNum=temp.get(temp.size()-1).getSortNum();
				m.setSortNum(sortNum+1);
				temp.add(m);
				map.put(pid, temp);
			}	
		}
		menuService.deleteIds(list);
        Set<Map.Entry<Long,List<Menu>>> set = map.entrySet();
        for (Iterator<Map.Entry<Long,List<Menu>>> it = set.iterator(); it.hasNext();) {
            Map.Entry<Long,List<Menu>> entry = (Map.Entry<Long,List<Menu>>) it.next();
            System.out.println(entry.getKey() + "--->" + entry.getValue());
            for(Menu me:entry.getValue()){
            	menuService.updateOrinsertMenu(me);
            }
        }
            
	}
		
	@RequestMapping(value="/edit/{id}")
	public String prepare(Model model,@PathVariable("id") Long id,
			@RequestParam("navtabid") String navtabid
		) {
		model.addAttribute("navtabid", navtabid);
		model.addAttribute("menu", menuService.getMenu(id));
		return "menu/edit";
	}
	
	@ResponseBody
	@RequestMapping("/save")
	public AjaxDone update(@ModelAttribute("menu")Menu menu,
			@RequestParam("tabid") String tabid
			) 
	{
		menuService.updateOrinsertMenu(menu);
		AjaxDone a=new AjaxDone();
		a.setStatusCode(200);
		a.setCallbackType("closeCurrent");
		a.setMessage("更新成功");
		a.setForwardUrl("");
		//a.setNavTabId(tabid); //重新加载这个nav
		return a;
	}
	
	
	
	
}
